package sea.explore;

import java.util.ArrayList;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import sea.util.PublicParam;
import sea.util.WinHelper;
import simhya.script.Symbol;

/**
 *
 * This class builds the layout of Range List
 * 
 * @author  Zhirun Ding
 * 
 * Created on 04/07/2012
 * 
 */

public class ExploreRangeForm extends javax.swing.JDialog {
    
    /** Creates new form ExploreForm */
    public ExploreRangeForm(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        
        //delete items of debug
        DefaultTableModel tm = (DefaultTableModel)rangeTable.getModel();
        for (int i = tm.getRowCount() - 1; i >=0; i--) {
            tm.removeRow(i);
        }                  
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        addButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        rangeTable = new javax.swing.JTable();
        backButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        helpButton = new javax.swing.JButton();
        add2Button = new javax.swing.JButton();
        delete2Button = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        rangeTable2 = new javax.swing.JTable();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane2.setViewportView(jTable1);

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable2.setName("jTable2"); // NOI18N
        jScrollPane3.setViewportView(jTable2);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(ExploreRangeForm.class);
        setTitle(resourceMap.getString("ExploreRangeForm.title")); // NOI18N
        setName("ExploreRangeForm"); // NOI18N
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setToolTipText(resourceMap.getString("jLabel1.toolTipText")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        addButton.setText(resourceMap.getString("addButton.text")); // NOI18N
        addButton.setName("addButton"); // NOI18N
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        deleteButton.setText(resourceMap.getString("deleteButton.text")); // NOI18N
        deleteButton.setName("deleteButton"); // NOI18N
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        rangeTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {new Boolean(false), "ki", "0.1", "1", "10", null},
                {null, "kr", "0.1", "1", "10", null}
            },
            new String [] {
                "Selected", "Name", "Min", "Max", "#Points", "Log"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        rangeTable.setName("rangeTable"); // NOI18N
        jScrollPane1.setViewportView(rangeTable);
        rangeTable.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("rangeTable.columnModel.title0")); // NOI18N
        rangeTable.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("rangeTable.columnModel.title1")); // NOI18N
        rangeTable.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("rangeTable.columnModel.title2")); // NOI18N
        rangeTable.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("rangeTable.columnModel.title3")); // NOI18N
        rangeTable.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("rangeTable.columnModel.title4")); // NOI18N
        rangeTable.getColumnModel().getColumn(5).setHeaderValue(resourceMap.getString("rangeTable.columnModel.title5")); // NOI18N

        backButton.setText(resourceMap.getString("backButton.text")); // NOI18N
        backButton.setName("backButton"); // NOI18N
        backButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButtonActionPerformed(evt);
            }
        });

        cancelButton.setText(resourceMap.getString("cancelButton.text")); // NOI18N
        cancelButton.setName("cancelButton"); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        helpButton.setText(resourceMap.getString("helpButton.text")); // NOI18N
        helpButton.setName("helpButton"); // NOI18N
        helpButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                helpButtonActionPerformed(evt);
            }
        });

        add2Button.setText(resourceMap.getString("add2Button.text")); // NOI18N
        add2Button.setName("add2Button"); // NOI18N
        add2Button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                add2ButtonActionPerformed(evt);
            }
        });

        delete2Button.setText(resourceMap.getString("delete2Button.text")); // NOI18N
        delete2Button.setName("delete2Button"); // NOI18N
        delete2Button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                delete2ButtonActionPerformed(evt);
            }
        });

        jScrollPane4.setName("jScrollPane4"); // NOI18N

        rangeTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Selected", "Name", "Value"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        rangeTable2.setName("rangeTable2"); // NOI18N
        jScrollPane4.setViewportView(rangeTable2);

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBox1.setName("jComboBox1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 525, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(25, 25, 25)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(69, 69, 69)
                                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 271, Short.MAX_VALUE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addGap(11, 11, 11)
                                        .addComponent(jLabel3)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 157, Short.MAX_VALUE)
                                        .addComponent(addButton, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(27, 27, 27)))
                                .addComponent(deleteButton)))))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 525, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(15, 15, 15)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 207, Short.MAX_VALUE)
                        .addComponent(add2Button, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(delete2Button)
                        .addGap(9, 9, 9)))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(295, Short.MAX_VALUE)
                .addComponent(cancelButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(backButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(helpButton)
                .addGap(8, 8, 8))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(deleteButton)
                    .addComponent(addButton)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(delete2Button)
                    .addComponent(add2Button)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(backButton)
                    .addComponent(helpButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    void addData(JTable rangeTable) {
        DefaultTableModel tm = (DefaultTableModel)rangeTable.getModel();
        //set the default value
        Object[] rowData = new Object[]{true, "", "", "", "", false};        
        //add row to table
        tm.addRow(rowData);
    }
    
    void deleteData(JTable rangeTable) {
        //System.out.println(rangeTable.getSelectedRow());
        if (rangeTable.getSelectedRow() == -1) {
            JOptionPane.showMessageDialog(this, "No row is selected,please select a row which you want to delete.");
        } else {
            DefaultTableModel tm = (DefaultTableModel)rangeTable.getModel();
            tm.removeRow(rangeTable.getSelectedRow());
        }
    }
    
    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
        this.addData(rangeTable);
    }//GEN-LAST:event_addButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        this.deleteData(rangeTable);
    }//GEN-LAST:event_deleteButtonActionPerformed

    //generate range params of explore
    public String toExploreRangeExpression() {
        String s = "";        
        
        //tow tables
        for (int k = 1; k <= 2; k++) {
            //get all data from table
            DefaultTableModel tm = null;
            if (k == 1) 
                tm = (DefaultTableModel)rangeTable.getModel();
            else
                tm = (DefaultTableModel)rangeTable2.getModel();
            //loop each row
            for (int i = 0; i < tm.getRowCount(); i++) {
                //if selected the param is selected
                boolean isSelected = false;
                if (tm.getValueAt(i, 0) != null) {
                    isSelected = Boolean.valueOf(tm.getValueAt(i, 0).toString());
                }
                if (isSelected) {
                    //Example: "range=[p1=1:10#10,p2=1:1e4#5log]" produces the following: 
                    //v1:v2#n[log]
                    String p = tm.getValueAt(i, 1).toString();
                    String v1 = tm.getValueAt(i, 2).toString();
                    String v2 = "";
                    String n = "";
                    boolean log = false;
                    if (k == 1) {
                        v2 = tm.getValueAt(i, 3).toString();
                        n = tm.getValueAt(i, 4).toString();
                        log = tm.getValueAt(i, 5) == null ? false : Boolean.valueOf(tm.getValueAt(i, 5).toString());
                    }
                    if (p.length() > 0 && v1.length() > 0 && v2.length() > 0 && n.length() > 0) {
                        if (s.length() > 0) s += ",";
                        s += p + "=" + v1 + ":" + v2 + "#" + n;
                        if (log) s += "log";
                    } else if (p.length() > 0 && v1.length() > 0) {
                        //p1=[1,2,3,4,5,6,7,8,9,10] and p2=[1,10,100,1000,10000]
                        if (s.length() > 0) s += ",";
                        s += p + "=[" + v1 + "]";
                    }                
                }
            }
        }
        
        if (s.length() > 0) {
            s = ",range=[" + s + "]";
        }
        
        //System.out.println(s);
        return s;
    }
    
    private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backButtonActionPerformed
        //update last editing cell
        if (rangeTable.getCellEditor() != null) {
            rangeTable.getCellEditor().stopCellEditing();
        }
        if (rangeTable2.getCellEditor() != null) {
            rangeTable2.getCellEditor().stopCellEditing();
        }
        
        toExploreRangeExpression();
        this.setVisible(false);
    }//GEN-LAST:event_backButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void helpButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpButtonActionPerformed
        WinHelper.showHelp("explore/range");
    }//GEN-LAST:event_helpButtonActionPerformed

    private void add2ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add2ButtonActionPerformed
        this.addData(rangeTable2);
    }//GEN-LAST:event_add2ButtonActionPerformed

    private void delete2ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delete2ButtonActionPerformed
        this.deleteData(rangeTable2);
    }//GEN-LAST:event_delete2ButtonActionPerformed

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        if (PublicParam.CurrentModelVariableName.equals(lastModelVariableName)) return;//has init combox for this variable
        
        lastModelVariableName = PublicParam.CurrentModelVariableName;
        JComboBox cbox = new JComboBox();
        ArrayList<Symbol> params = PublicParam.SimHyACommand.getExplorableParameters(PublicParam.CurrentModelVariableName);        
        for (int i = 0; i < params.size(); i++) {
            cbox.addItem(params.get(i).name);
            //set default value
            //Object[] rowData = new Object[]{false, params.get(i).name, "", "", "", false};        
            //add row to table
            //tm.addRow(rowData);             
        }
        
        TableCellEditor edt = new DefaultCellEditor(cbox);
        rangeTable.getColumnModel().getColumn(1).setCellEditor(edt);
        rangeTable2.getColumnModel().getColumn(1).setCellEditor(edt);      
    }//GEN-LAST:event_formComponentShown
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                ExploreRangeForm dialog = new ExploreRangeForm(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton add2Button;
    private javax.swing.JButton addButton;
    private javax.swing.JButton backButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton delete2Button;
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton helpButton;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTable rangeTable;
    private javax.swing.JTable rangeTable2;
    // End of variables declaration//GEN-END:variables
    private String lastModelVariableName = "";
}
